

package twitter;

import twitter4j.DirectMessage;
import twitter4j.Paging;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import hibernate.util.SessionFactoryUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

/*this class saves the direct messages to the database*/
public class GetDirectMessages {
  
    public static void main(String[] args) {
        Twitter twitter = new TwitterFactory().getInstance();
        Session session = SessionFactoryUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        TweetDetails details=new TweetDetails();



        try {
            Paging paging = new Paging(1);
            List<DirectMessage> messages;
             {
                messages = twitter.getDirectMessages(paging);
                for (DirectMessage message : messages) {
                     tx.begin();
    details.setUserID(message.getSenderScreenName());
    details.setTweet(message.getText());
    details.setUserTime(message.getCreatedAt());
    session.save(details);
    tx.commit();
                }
                paging.setPage(paging.getPage() + 1);
            } 
            System.out.println("done.");
    session.close();
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get messages: " + te.getMessage());
            System.exit(-1);
        }
    }
}
